<template>
  <div>
    <a-switch
      :model-value="modelValue"
      :check-value="checkValue"
      :uncheck-value="uncheckValue"
      :loading="loading"
      :disabled="disabled"
      :size="size"
      class="h-auto"
      @update:model-value="handleChange"></a-switch>
    <slot name="tip"></slot>
  </div>
</template>

<script setup lang="ts">
interface IEmit {
  (event: 'update:modelValue', value: number): void
  (event: 'before-change', value: number): void
}

interface IProps {
  modelValue: number
  confirm?: PromiseFn
  checkValue?: number
  uncheckValue?: number
  disabled?: boolean
  size?: 'small' | 'medium'
}

const emit = defineEmits<IEmit>()
const props = withDefaults(defineProps<IProps>(), {
  checkValue: 1,
  uncheckValue: 2,
  disabled: false,
  size: 'small'
})

const loading = ref(false)

async function handleChange(val: number) {
  if (!props.confirm) {
    emit('update:modelValue', val)
    return
  }
  try {
    loading.value = true
    await props.confirm(val)
    emit('update:modelValue', val)
  } catch {
    loading.value = false
  } finally {
    loading.value = false
  }
}
</script>

<style scoped lang="less"></style>
